// 我的理解是bfs, 而不是dfs, bfs算是全搜, 有几个点都会被搜到,  而dfs效率太低, 每个点都需要单独搜
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let m, n; // m行, n列
let initArr = [];
rl.on("line", (line) => {
    if (m === undefined) {
        [n, m] = line.trim().split(" ").map(Number)
    } else {
        initArr.push(line.trim().split(" ").map(Number))
        if (initArr.length === m) {
            console.log(getResult(m, n, initArr))
            // clear
            m = n = undefined
            initArr.length = 0
        }

    }

})

function getResult(m, n, initArr) {
    let person = []
    let visited = new Array(m).fill(null).map(_ => new Array(n).fill(false))
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (initArr[i][j] === 2) {
                person.push([i, j])
            } else if (initArr[i][j] === 1) {
                visited[i][j] = true
            }
        }
    }

    // 找到小华, bfs, 记录有几个点可达
    // 找到小为, bfs, 记录有几个点可达
    let arr1 = []
    let arr2 = []
    let pq1 = [person[0]]
    let pq2 = [person[1]]
    bfs(JSON.parse(JSON.stringify(visited)), pq1, arr1, m, n, initArr)
    bfs(JSON.parse(JSON.stringify(visited)), pq2, arr2, m, n, initArr)

    // 找公共点
    let count = 0
    for (const str of arr1) {
        if (arr2.indexOf(str) !== -1) {
            count++
        }
    }
    return count
}

function bfs(visited, pq, res, m, n, initArr) {
    while (pq.length) {
        const [x, y] = pq.shift()
        visited[x][y] = true
        let direction = [
            [-1, 0],
            [1, 0],
            [0, -1],
            [0, 1]
        ]
        for (const [a, b] of direction) {
            let newX = x + a
            let newY = y + b
            if (newX >= 0 && newX < m && newY >= 0 && newY < n) {
                if (visited[newX][newY]) continue
                if (initArr[newX][newY] === 3) {
                    res.push(`${newX}-${newY}`)
                }
                pq.push([newX, newY])
            }
        }
    }
}

